import React, { Component } from 'react'

import cateModel from '../../models/cateModel'

import {
  CateListContainer
} from './style'

class Cate extends Component {

  state = {
    activeList: [],
    cateList: [],
    cateInfoList: []
  }
  // 点击事件
  activeFn = index => {
    let activeList = this.state.activeList.map(item => '')
    activeList[index] = 'active'

    let cateInfoList = this.state.cateList[index][1]

    this.setState({ activeList, cateInfoList })
  }

  // 数组 字符串
  async componentDidMount() {
    let ret = await cateModel.getCate()
    let jsonObj = ret.data.data.category
    // 把对象转为数据[key,数据]
    let jsonArr = Object.entries(jsonObj)
    // 填充指定长度的数组
    let activeList = new Array(jsonArr.length).fill('')
    activeList[0] = 'active'
    let cateInfoList = jsonArr[0][1]
    this.setState({
      cateList: jsonArr,
      activeList,
      cateInfoList
    })
  }

  render() {
    return (
      <CateListContainer>
        <div>
          <ul>
            {
              this.state.cateList.length === 0 ? <div>加载中</div> : (
                <>
                  {
                    this.state.cateList.map((item, index) => (
                      <li key={item[0]} onClick={this.activeFn.bind(this, index)} className={this.state.activeList[index]}><span>{item[0]}</span></li>
                    ))
                  }
                </>
              )
            }

          </ul>
        </div >
        <div>
          <ul>
            {
              this.state.cateInfoList.map(item=>(
                <li key={item}>{item}</li>
              ))
            }
           
          </ul>
        </div>
      </CateListContainer >
    );
  }
}

export default Cate;
